package com.xueyi.game.backend.config;

import com.alibaba.fastjson2.JSON;
import com.xueyi.core.base.BaseResponse;
import com.xueyi.core.base.JwtResponse;
import com.xueyi.core.constants.SystemCode;
import com.xueyi.core.utils.JWTUtil;
import com.xueyi.core.utils.LogUtil;
import com.xueyi.game.backend.entity.po.BaseUser;
import com.xueyi.starter.utils.JedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;

/**
 * 描述 网关Config
 *
 * @auther 俞烨
 * @date 2022-11-17 13
 */
@SpringBootConfiguration
@Aspect
public class GatewayConfig {

    public static final List<String> EXCLUDE_PATH_ARR = Collections.singletonList("/game/backend/login");
    /**
     * 当前登录的后台用户信息
     */
    public static ThreadLocal<BaseUser> USER_LOCAL = new ThreadLocal<>();
    @Autowired
    HttpServletRequest request;
    @Autowired
    BaseSqlConfig baseSqlConfig;
    @Autowired
    JedisUtil jedisUtil;
    @Autowired
    LogUtil logUtil;
    @Autowired
    RedissonClient redissonClient;

    /**
     * 后台的权限校验
     *
     * @param pjp
     * @return
     */
    @Around("backendController()")
    public Object backendAuthorityCheck(ProceedingJoinPoint pjp) throws Throwable {

        logUtil.info("系统名称：{} , 请求路径： {} , 入参信息：{}", "知识易付后台", request.getRequestURI(),
                pjp.getArgs() == null ? "无参数" : pjp.getArgs());
        Object resultObj = null;
        JWTUtil.Result parseSignResult = null;
        if (!EXCLUDE_PATH_ARR.contains(request.getRequestURI())) {
            //通过请求头获取token
            String authorization = request.getHeader("Authorization");
            //判断获取到到token与存储等待token对比如果是则不拦截
            if (StringUtils.isBlank(authorization) && !StringUtils.isBlank(request.getParameter("exportToken"))) {
                authorization = request.getParameter("Authorization");
            }
            if (StringUtils.isBlank(authorization)) {
                //如果token为bull则报错，重新登录
                return BaseResponse.build(SystemCode.USER_NOT_LOGIN, "用户没有登录");
            }

            //获取jedis实例
            try {

                // 解析内容
                parseSignResult = JWTUtil.parseSign(authorization);
                if (!parseSignResult.getCode().equals(SystemCode.SUCCESS) || parseSignResult.getDecodedJWT() == null) {
                    return BaseResponse.build(parseSignResult.getCode(), "用户登录过期，请重新登录");
                }

                BaseUser baseUser = JSON.parseObject(parseSignResult.claim("userInfo").asString(), BaseUser.class);
                // 查询当前的用户信息是否需要校验商户的基本内容
                if (CollectionUtils.isEmpty(baseUser.getRoleList())) {
                    return BaseResponse.build(SystemCode.USER_NOT_LOGIN, "用户权限获取失败，请重新登录");
                }

                USER_LOCAL.set(baseUser);
                resultObj = pjp.proceed();

                // 判断过期时间是否大于指定的更换时间，如果大于的话就更换JWT的签名信息
                JWTUtil.ChangeSignResult newSign = JWTUtil.changeJwtSign(parseSignResult, BaseUser.class);

                if (org.springframework.util.StringUtils.hasLength(newSign.getSign()) && resultObj instanceof BaseResponse) {
                    BaseResponse<Object> response = (BaseResponse<Object>) resultObj;
                    JwtResponse<Object> objectJwtResponse = new JwtResponse<>();
                    BeanUtils.copyProperties(response, objectJwtResponse);
                    objectJwtResponse.setJwtSign(newSign.getSign());
                    resultObj = objectJwtResponse;
                }

            } finally {
                USER_LOCAL.remove();
            }
        } else {
            resultObj = pjp.proceed();
        }

        logUtil.info("系统名称：{} , 请求路径： {} , 响应结果：{} ", "知识易付后台", request.getRequestURI(),
                pjp.getArgs() == null ? "无参数" : resultObj);

        return resultObj;
    }

    @Pointcut("execution(* com.xueyi.game.backend.controller..*(..))")
    public void backendController() {
    }
}
